package com.meta.pic.view

import android.graphics.Color
import android.os.Bundle
import android.view.Gravity
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.view.ViewGroup.LayoutParams.MATCH_PARENT
import android.view.ViewGroup.LayoutParams.WRAP_CONTENT
import android.widget.*
import androidx.core.widget.addTextChangedListener
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.StaggeredGridLayoutManager
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout
import com.airbnb.epoxy.EpoxyRecyclerView
import com.airbnb.mvrx.BaseMvRxFragment
import com.airbnb.mvrx.fragmentViewModel
import com.airbnb.mvrx.withState
import com.meta.pic.*
import com.meta.pic.util.BaseEpoxyController
import com.meta.pic.util.createGridLookup
import com.meta.pic.util.simpleController

class HomeFragment : BaseMvRxFragment() {
    private val viewModel: HomeViewModel by fragmentViewModel()
    private val gridLayoutManager by lazy(LazyThreadSafetyMode.NONE) {
        GridLayoutManager(requireContext(),
            GRID_SPAN_SIZE
        )
    }
    private val staggeredGridLayoutManager by lazy(LazyThreadSafetyMode.NONE) {
        StaggeredGridLayoutManager(2, StaggeredGridLayoutManager.VERTICAL)
    }

    companion object {
        private const val TAG = "HomeFragment"
        private const val GRID_SPAN_SIZE = 3
    }

    private val rootView by lazy(LazyThreadSafetyMode.NONE) {
        LinearLayout(requireContext()).apply {
            orientation = LinearLayout.VERTICAL
            addView(toolbar)
            addView(swipeRefreshLayout)
        }
    }

    private val editText by lazy(LazyThreadSafetyMode.NONE) {
        EditText(context).apply {
            hint = "请输入地点"
            setHintTextColor(Color.BLACK)
            setTextColor(Color.BLACK)
            addTextChangedListener {
                viewModel.setLocation(it?.toString() ?: "")
            }
            layoutParams = LinearLayout.LayoutParams(0, WRAP_CONTENT).apply {
                weight = 1F
            }

        }
    }

    private val toolbar by lazy(LazyThreadSafetyMode.NONE) {
        LinearLayout(requireContext()).apply {
            layoutParams = LinearLayout.LayoutParams(MATCH_PARENT, WRAP_CONTENT)
            gravity = Gravity.CENTER
            addView(editText)
            addView(Button(context).apply {
                text = "搜索"
                setOnClickListener {
                    withState(viewModel) {
                        if (it.location.isEmpty()){
                            Toast.makeText(requireContext(), "请输入", Toast.LENGTH_LONG).show()
                            return@withState
                        }
                        onRefresh()
                    }
                }
            })
            addView(Button(context).apply {
                text = "切换布局"
                setOnClickListener {
                    viewModel.toggleLayoutType()
                }
            })
        }
    }
    private val swipeRefreshLayout by lazy(LazyThreadSafetyMode.NONE) {
        SwipeRefreshLayout(requireContext()).apply {
            layoutParams = LinearLayout.LayoutParams(MATCH_PARENT, MATCH_PARENT)
            addView(recyclerView)
            setOnRefreshListener {
                onRefresh()
            }
        }
    }

    private fun onRefresh() {
        showRefreshing(true)
        viewModel.loadData(false)
        recyclerView.post {
            recyclerView.smoothScrollToPosition(0)
        }
    }


    private fun loadMore() {
        viewModel.loadData(true)
    }

    private val recyclerView by lazy(LazyThreadSafetyMode.NONE) {
        EpoxyRecyclerView(requireContext()).apply {
            layoutParams = FrameLayout.LayoutParams(MATCH_PARENT, MATCH_PARENT)
            layoutManager = gridLayoutManager
            setController(epoxyController)
        }
    }

    private val epoxyController by lazy(LazyThreadSafetyMode.NONE) {
        simpleController(viewModel) { state ->
            state.list.forEachIndexed { index, item ->
                picItemView {
                    id("${item.id}_$index")
                    model(item)
                }
            }
            if (state.nextPage > 0) {
                verticalLoadingView {
                    id("laodmore_${state.list.size}")
                    onBind { model, view, position ->
                        loadMore()
                    }
                }
            }
        }
    }


    private fun showRefreshing(show: Boolean) {
        if (!swipeRefreshLayout.isEnabled) {
            swipeRefreshLayout.post {
                swipeRefreshLayout.isRefreshing = false
            }
            return
        }
        swipeRefreshLayout.post {
            if (show == swipeRefreshLayout.isRefreshing) return@post
            swipeRefreshLayout.isRefreshing = show
        }
    }


    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        epoxyController.onRestoreInstanceState(savedInstanceState)

        viewModel.asyncSubscribe(this, HomeState::request, onFail = {
            showRefreshing(false)
            Toast.makeText(requireContext(), it.message, Toast.LENGTH_LONG).show()
        }, onSuccess = {
            showRefreshing(false)
        })
        onRefresh()
    }

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? = rootView


    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        setGridLookUp()
    }

    override fun onSaveInstanceState(outState: Bundle) {
        super.onSaveInstanceState(outState)
        epoxyController.onSaveInstanceState(outState)
    }

    override fun onDestroy() {
        epoxyController.cancelPendingModelBuild()
        super.onDestroy()
    }

    override fun invalidate() {
        withState(viewModel) {
            if (it.location != editText.editableText.toString()) {
                editText.setText(it.location)
                editText.setSelection(it.location.length)
            }
            if (it.layoutType == HomeState.GRID) {
                if (recyclerView.layoutManager !is GridLayoutManager) {
                    recyclerView.layoutManager = gridLayoutManager
                    setGridLookUp()
                }
            } else {
                if (recyclerView.layoutManager !is StaggeredGridLayoutManager) {
                    recyclerView.layoutManager = staggeredGridLayoutManager
                }
            }

        }
        if (recyclerView.adapter == null) {
            recyclerView.setController(epoxyController)
        }
        epoxyController.requestModelBuild()
    }


    private fun setGridLookUp() {
        if (recyclerView.layoutManager !is GridLayoutManager) return
        (epoxyController as? BaseEpoxyController)?.setLookup(recyclerView.createGridLookup {
            if (it is PicItemView_) {
                1
            } else {
                GRID_SPAN_SIZE
            }
        })
    }
}